
from flask import Blueprint, jsonify, request, render_template
from python.extensions import db
from python.model.weather import WeatherData
from datetime import datetime
from sqlalchemy import func, extract

# 创建温度蓝图
temp_bp = Blueprint('temperature', __name__, url_prefix='/temperature')


@temp_bp.route('/high_contrast', methods=['GET'])
def high_contrast_page():
    """高对比度温度分析仪表盘"""
    try:
        # 获取所有城市（过滤空值）
        cities_query = db.session.query(WeatherData.city).distinct().all()
        cities = [city[0] for city in cities_query if city[0] and city[0].strip()]

        # 获取所有年份（过滤空值）
        years_query = db.session.query(extract('year', WeatherData.date)).distinct().all()
        years = [int(year[0]) for year in years_query if year[0] is not None]
        years = sorted(years, reverse=True)

        return render_template('menu/temperature_high_contrast.html', cities=cities, years=years)
    except Exception as e:
        # 在实际应用中，应该记录错误日志
        print(f"Error in high_contrast_page: {str(e)}")
        return render_template('error.html', message="加载页面时出错，请稍后再试"), 500


@temp_bp.route('/monthly_high', methods=['GET'])
def monthly_high_temperature():
    """获取月度最高温度数据"""
    return fetch_monthly_temperature('max_temp', 'max')


@temp_bp.route('/monthly_low', methods=['GET'])
def monthly_low_temperature():
    """获取月度最低温度数据"""
    return fetch_monthly_temperature('min_temp', 'min')


def fetch_monthly_temperature(temp_field, agg_func):
    """通用月度温度数据获取函数"""
    city = request.args.get('urban', '上海')
    year = request.args.get('year', None)

    # 构建基础查询
    query = db.session.query(
        func.date_format(WeatherData.date, '%Y-%m').label('month'),
        getattr(func, agg_func)(getattr(WeatherData, temp_field)).label('temp_value')
    ).filter(WeatherData.city == city)

    # 按年份过滤
    if year:
        try:
            year_int = int(year)
            query = query.filter(extract('year', WeatherData.date) == year_int)
        except ValueError:
            return jsonify({'error': '年份参数无效'}), 400

    # 分组并排序
    results = query.group_by('month').order_by('month').all()

    # 处理结果
    months = [result.month for result in results]
    temps = [float(result.temp_value) for result in results]

    return jsonify({
        'months': months,
        'temps': temps
    })


@temp_bp.route('/compare', methods=['GET'])
def compare_temperatures():
    """
    比较两个日期范围的温度数据
    参数:
        start_date1: 第一个日期范围的开始日期 (YYYY-MM-DD)
        end_date1: 第一个日期范围的结束日期 (YYYY-MM-DD)
        start_date2: 第二个日期范围的开始日期 (YYYY-MM-DD)
        end_date2: 第二个日期范围的结束日期 (YYYY-MM-DD)
        city: 城市名称 (默认为'上海')
    """
    # 获取请求参数
    start_date1 = request.args.get('start_date1')
    end_date1 = request.args.get('end_date1')
    start_date2 = request.args.get('start_date2')
    end_date2 = request.args.get('end_date2')
    city = request.args.get('city', '上海')  # 默认为上海

    # 验证参数是否存在
    if not all([start_date1, end_date1, start_date2, end_date2]):
        return jsonify({'error': '缺少必要的日期参数'}), 400

    try:
        # 转换日期格式
        start1 = datetime.strptime(start_date1, '%Y-%m-%d').date()
        end1 = datetime.strptime(end_date1, '%Y-%m-%d').date()
        start2 = datetime.strptime(start_date2, '%Y-%m-%d').date()
        end2 = datetime.strptime(end_date2, '%Y-%m-%d').date()
    except ValueError:
        return jsonify({'error': '日期格式不正确，请使用YYYY-MM-DD格式'}), 400

    # 查询并处理两个时间段的数据
    period1 = fetch_period_data(start1, end1, city)
    period2 = fetch_period_data(start2, end2, city)

    # 计算平均温度
    avg_period1 = calculate_averages(period1)
    avg_period2 = calculate_averages(period2)

    # 构造响应数据
    response = {
        'period1': {
            'start_date': start_date1,
            'end_date': end_date1,
            'days': len(period1),
            'data': period1,
            'avg_temperatures': avg_period1
        },
        'period2': {
            'start_date': start_date2,
            'end_date': end_date2,
            'days': len(period2),
            'data': period2,
            'avg_temperatures': avg_period2
        },
        'comparison': {
            'max_temp_diff': round(avg_period2['max'] - avg_period1['max'], 1),
            'min_temp_diff': round(avg_period2['min'] - avg_period1['min'], 1)
        }
    }

    return jsonify(response)


def fetch_period_data(start_date, end_date, city):
    """获取指定日期范围内的温度数据"""
    data = WeatherData.query.filter(
        WeatherData.date.between(start_date, end_date),
        WeatherData.city == city
    ).order_by(WeatherData.date).all()

    return [{
        'date': record.date.strftime('%Y-%m-%d'),
        'max_temp': record.max_temp,
        'min_temp': record.min_temp,
        'weather': record.weather
    } for record in data]


def calculate_averages(data):
    """计算平均最高温度和最低温度"""
    if not data:
        return {'max': 0, 'min': 0}

    max_sum = sum(item['max_temp'] for item in data)
    min_sum = sum(item['min_temp'] for item in data)

    return {
        'max': round(max_sum / len(data), 1),
        'min': round(min_sum / len(data), 1)
    }


@temp_bp.route('/trend', methods=['GET'])
def temperature_trend():
    """
    获取指定日期范围内的温度趋势
    参数:
        start_date: 开始日期 (YYYY-MM-DD)
        end_date: 结束日期 (YYYY-MM-DD)
        city: 城市名称 (默认为'上海')
    """
    # 获取请求参数
    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')
    city = request.args.get('city', '上海')

    # 验证参数
    if not all([start_date, end_date]):
        return jsonify({'error': '缺少日期参数'}), 400

    try:
        # 转换日期格式
        start = datetime.strptime(start_date, '%Y-%m-%d').date()
        end = datetime.strptime(end_date, '%Y-%m-%d').date()
    except ValueError:
        return jsonify({'error': '日期格式不正确，请使用YYYY-MM-DD格式'}), 400

    # 查询数据
    data = WeatherData.query.filter(
        WeatherData.date.between(start, end),
        WeatherData.city == city
    ).order_by(WeatherData.date).all()

    # 处理数据
    trend_data = [{
        'date': record.date.strftime('%Y-%m-%d'),
        'max_temp': record.max_temp,
        'min_temp': record.min_temp,
        'weather': record.weather,
        'wind_level': record.wind_level
    } for record in data]

    return jsonify({
        'start_date': start_date,
        'end_date': end_date,
        'city': city,
        'data_count': len(trend_data),
        'trend_data': trend_data
    })


@temp_bp.route('/daily', methods=['GET'])
def daily_weather():
    """
    获取特定日期的天气详情
    参数:
        date: 查询日期 (YYYY-MM-DD)
        city: 城市名称 (默认为'上海')
    """
    # 获取请求参数
    date_str = request.args.get('date')
    city = request.args.get('city', '上海')

    if not date_str:
        return jsonify({'error': '缺少日期参数'}), 400

    try:
        # 转换日期格式
        query_date = datetime.strptime(date_str, '%Y-%m-%d').date()
    except ValueError:
        return jsonify({'error': '日期格式不正确，请使用YYYY-MM-DD格式'}), 400

    # 查询数据
    weather = WeatherData.query.filter_by(date=query_date, city=city).first()

    if not weather:
        return jsonify({'error': '未找到指定日期的天气数据'}), 404

    # 构造响应数据
    return jsonify({
        'date': weather.date.strftime('%Y-%m-%d'),
        'max_temp': weather.max_temp,
        'min_temp': weather.min_temp,
        'weather': weather.weather,
        'wind': weather.wind,
        'aqi': weather.aqi,
        'aqi_level': weather.aqi_level,
        'wind_level': weather.wind_level,
        'city': weather.city
    })